//
//  ConfirmDeleteHomeView.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/22.
//

#import "ConfirmDeleteHomeView.h"
#import "UIImageView+WebCache.h"

@interface ConfirmDeleteHomeView ()

@property (nonatomic,strong) UILabel *adminLabel;

@end

@implementation ConfirmDeleteHomeView

- (instancetype)initWithFrame:(CGRect)frame
                    GroupInfo:(NSDictionary *)groupInfo
                      IsAdmin:(BOOL)isAdmin
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.masksToBounds = YES;
        [self initViewWithGroupInfo:groupInfo IsAdmin:isAdmin];
    }
    return self;
}

- (void)initViewWithGroupInfo:(NSDictionary *)groupInfo
                      IsAdmin:(BOOL)isAdmin
{
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 312)];
    infoView.layer.masksToBounds = YES;
    [infoView.layer setCornerRadius:40];
    infoView.backgroundColor = RealWhiteColor;
    [self addSubview:infoView];
    
    UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(infoView.width-46, 16, 30, 30)];
    [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
    [infoView addSubview:close];
    [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((infoView.width-52)/2, 40, 52, 50)];
    img.image = [UIImage imageNamed:@"exit_group"];
    [infoView addSubview:img];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, img.maxY+28, infoView.width-32, 28)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = [NSString stringWithFormat:@"即将退出家庭“%@”",groupInfo[@"groupInfo"][@"name"]];
    title.textColor = BlackColor;
    title.font = MEDIUM_FONT(20);
    title.numberOfLines = 0;
    [title sizeToFit];
    [title setFrame:CGRectMake(16, img.maxY+28, infoView.width-32, title.height+8)];
    [infoView addSubview:title];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(title.frame)+6, infoView.width, 48)];
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.text = @"退出后，将无法与家庭成员共享位置\n轨迹等数据将被清除";
    subTitle.textColor = GraryLightColor;
    subTitle.font = DEFAULT_FONT(14);
    subTitle.numberOfLines = 2;
    [infoView addSubview:subTitle];
        
    __block NSString *newAdminId;
    if (isAdmin) {
        NSMutableArray *memberArray = [NSMutableArray array];
        for (NSDictionary *dic in groupInfo[@"userInfo"]) {
            if ([dic[@"userId"] integerValue] != [XDXShareInstance shareInstance].userId.integerValue) {
                [memberArray addObject:dic];
            }
        }
        if ([groupInfo[@"userInfo"] count]>2) {
            UIView *avatarView = [[UIView alloc] initWithFrame:CGRectMake(32, subTitle.maxY+28, infoView.width-64, 66)];
            avatarView.backgroundColor = LightBGColor;
            avatarView.layer.masksToBounds = YES;
            [avatarView.layer setCornerRadius:16];
            [infoView addSubview:avatarView];
                    
            newAdminId = memberArray.firstObject[@"userId"];
            if (memberArray.count>5) {
                avatarView.height = 118;
                
                UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 12, 42, 42)];
                [avatarView addSubview:view1];
                for (int i = 0; i < 5; i ++) {
                    NSDictionary *dic = memberArray[i];
                    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(i*52, 0, 42, 42)];
                    img.userInteractionEnabled = YES;
                    img.tag = 100+i;
                    [img.layer setBorderWidth:2];
                    [img.layer setBorderColor:(newAdminId.integerValue==[dic[@"userId"] integerValue])?DeepMainCoolor.CGColor:[UIColor clearColor].CGColor];
                    img.layer.masksToBounds = YES;
                    [img.layer setCornerRadius:12];
                    [img sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]]];
                    [view1 addSubview:img];
                    
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
                    [[tap rac_gestureSignal] subscribeNext:^(id x) {
                        for (int i = 0; i < memberArray.count; i ++) {
                            [self viewWithTag:100+i].layer.borderColor = [UIColor clearColor].CGColor;
                        }
                        [img.layer setBorderColor:DeepMainCoolor.CGColor];
                        
                        newAdminId = dic[@"userId"];
                        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"选择 %@ 成为管理员",dic[@"nickName"]]];
                        [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(3,[dic[@"nickName"] length])];
                        [str addAttribute:NSFontAttributeName value:MEDIUM_FONT(15) range:NSMakeRange(3,[dic[@"nickName"] length])];
                        self.adminLabel.attributedText = str;
                    }];
                    [img addGestureRecognizer:tap];
                }
                [view1 setFrame:CGRectMake((avatarView.width-250)/2, 12, 250, 42)];
                
                UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 64, 42, 42)];
                [avatarView addSubview:view2];
                for (int i = 5; i < memberArray.count; i ++) {
                    NSDictionary *dic = memberArray[i];
                    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((i-5)*52, 0, 42, 42)];
                    img.userInteractionEnabled = YES;
                    img.tag = 100+i;
                    [img.layer setBorderWidth:2];
                    [img.layer setBorderColor:(newAdminId.integerValue==[dic[@"userId"] integerValue])?DeepMainCoolor.CGColor:[UIColor clearColor].CGColor];
                    img.layer.masksToBounds = YES;
                    [img.layer setCornerRadius:12];
                    [img sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]]];
                    [view2 addSubview:img];
                    
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
                    [[tap rac_gestureSignal] subscribeNext:^(id x) {
                        for (int i = 0; i < memberArray.count; i ++) {
                            [self viewWithTag:100+i].layer.borderColor = [UIColor clearColor].CGColor;
                        }
                        [img.layer setBorderColor:DeepMainCoolor.CGColor];
                        
                        newAdminId = dic[@"userId"];
                        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"选择 %@ 成为管理员",dic[@"nickName"]]];
                        [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(3,[dic[@"nickName"] length])];
                        [str addAttribute:NSFontAttributeName value:MEDIUM_FONT(15) range:NSMakeRange(3,[dic[@"nickName"] length])];
                        self.adminLabel.attributedText = str;
                    }];
                    [img addGestureRecognizer:tap];
                    
                    if (i==(memberArray.count-1)) {
                        [view2 setFrame:CGRectMake((avatarView.width-img.maxX)/2, 64, img.maxX, 42)];
                    }
                }
            }else{
                UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 12, 42, 42)];
                [avatarView addSubview:view2];
                for (int i = 0; i < memberArray.count; i ++) {
                    NSDictionary *dic = memberArray[i];
                    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(i*52, 0, 42, 42)];
                    img.userInteractionEnabled = YES;
                    img.tag = 100+i;
                    [img.layer setBorderWidth:2];
                    [img.layer setBorderColor:(newAdminId.integerValue==[dic[@"userId"] integerValue])?DeepMainCoolor.CGColor:[UIColor clearColor].CGColor];
                    img.layer.masksToBounds = YES;
                    [img.layer setCornerRadius:12];
                    [img sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]]];
                    [view2 addSubview:img];
                    
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
                    [[tap rac_gestureSignal] subscribeNext:^(id x) {
                        for (int i = 0; i < memberArray.count; i ++) {
                            [self viewWithTag:100+i].layer.borderColor = [UIColor clearColor].CGColor;
                        }
                        [img.layer setBorderColor:DeepMainCoolor.CGColor];
                        
                        newAdminId = dic[@"userId"];
                        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"选择 %@ 成为管理员",dic[@"nickName"]]];
                        [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(3,[dic[@"nickName"] length])];
                        [str addAttribute:NSFontAttributeName value:MEDIUM_FONT(15) range:NSMakeRange(3,[dic[@"nickName"] length])];
                        self.adminLabel.attributedText = str;
                    }];
                    [img addGestureRecognizer:tap];
                    
                    if (i==(memberArray.count-1)) {
                        [view2 setFrame:CGRectMake((avatarView.width-img.maxX)/2, 12, img.maxX, 42)];
                    }
                }
            }
            infoView.height = avatarView.maxY+140;
            
            _adminLabel = [[UILabel alloc] initWithFrame:CGRectMake(32, infoView.height-130, infoView.width-64, 18)];
            _adminLabel.textColor = [GraryHeavyLightColor colorWithAlphaComponent:0.6];
            _adminLabel.font = DEFAULT_FONT(15);
            _adminLabel.textAlignment = NSTextAlignmentCenter;
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"选择 %@ 成为管理员",memberArray.firstObject[@"nickName"]]];
            [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(3,[memberArray.firstObject[@"nickName"] length])];
            [str addAttribute:NSFontAttributeName value:MEDIUM_FONT(15) range:NSMakeRange(3,[memberArray.firstObject[@"nickName"] length])];
            _adminLabel.attributedText = str;
            [infoView addSubview:_adminLabel];
        }else if ([groupInfo[@"userInfo"] count]>0){
            newAdminId = memberArray.firstObject[@"userId"];
            infoView.height = subTitle.maxY+112;
        }
    }else{
        infoView.height = subTitle.maxY+112;
    }

    NSArray *array = @[@"不是现在",@"退出"];
    for (int i = 0; i < array.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(32+i*((infoView.width-80)/2+16), infoView.height-84, (infoView.width-80)/2, 54)];
        button.layer.masksToBounds = YES;
        [button.layer setCornerRadius:27];
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button.titleLabel setFont:MEDIUM_FONT(16)];
        if (i==0) {
            button.backgroundColor = LightBGColor;
            [button setTitleColor:RealBlackColor forState:UIControlStateNormal];
        }else{
            button.backgroundColor = RedColor;
            [button setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        }
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (i==0) {
                [UIView animateWithDuration:0.3 animations:^{
                    infoView.y = SCREEN_HEIGHT;
                    self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
                } completion:^(BOOL finished) {
                    [self removeFromSuperview];
                }];
            }else if (i==1){
                NSDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:[XDXShareInstance shareInstance].userId forKey:@"userId"];
                [param setValue:groupInfo[@"groupInfo"][@"id"] forKey:@"groupId"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/system/group/removeusers"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200) {
                        if (newAdminId.integerValue>0) {
                            NSDictionary *param = [NSMutableDictionary dictionary];
                            [param setValue:newAdminId forKey:@"newAdminId"];
                            [param setValue:groupInfo[@"groupInfo"][@"id"] forKey:@"groupId"];
                            CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                            [manager encryptedPOST:@"/system/group/setadminuserandremoveself"
                            parameters:param
                            success:^(NSDictionary *responseObject) {
                                
                            }
                            failure:^(NSError *aError) {
                                
                            }];
                        }
                        
                        [UIView animateWithDuration:0.3 animations:^{
                            infoView.y = SCREEN_HEIGHT;
                            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
                        } completion:^(BOOL finished) {
                            [self removeFromSuperview];
                            if (self.ConfirmDeleteBlock) {
                                self.ConfirmDeleteBlock();
                            }
                        }];
                    }
                    [[HCToast shareInstance] showToast:responseObject[@"msg"]];
                }
                failure:^(NSError *aError) {
                    
                }];
            }
        }];
        [infoView addSubview:button];
    }
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self insertSubview:bgView atIndex:0];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
    [bgView addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        infoView.y = SCREEN_HEIGHT-infoView.height-34;
        self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
    }];
}

@end
